import { defineStore } from 'pinia'

export const useDeviceStore = defineStore('device', {
  state: () => ({
    currentDevice: null,
    deviceList: [],
    loading: false,
    error: null
  }),

  getters: {
    hasCurrentDevice: (state) => !!state.currentDevice,
    currentDeviceId: (state) => state.currentDevice?.id
  },

  actions: {
    setCurrentDevice(device) {
      this.currentDevice = device
      // 保存到本地存储
      if (device) {
        localStorage.setItem('currentDevice', JSON.stringify(device))
      } else {
        localStorage.removeItem('currentDevice')
      }
    },

    async fetchDeviceList() {
      this.loading = true
      try {
        const token = localStorage.getItem('token')
        const response = await fetch('https://penglink.pcwxcn.top/api/device/list', {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Accept': 'application/json'
          }
        })

        if (!response.ok) {
          throw new Error('获取设备列表失败')
        }

        const result = await response.json()
        if (result.code === 200) {
          this.deviceList = result.data
          
          // 恢复当前设备
          const savedDevice = localStorage.getItem('currentDevice')
          if (savedDevice) {
            const device = JSON.parse(savedDevice)
            // 确保设备仍然存在于列表中
            if (this.deviceList.find(d => d.id === device.id)) {
              this.setCurrentDevice(device)
            } else {
              this.setCurrentDevice(null)
            }
          }
        }
      } catch (error) {
        this.error = error.message
        console.error('获取设备列表失败:', error)
      } finally {
        this.loading = false
      }
    },

    clearCurrentDevice() {
      this.setCurrentDevice(null)
    }
  }
})
